<?php

namespace app\common\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Cache;
use think\Log;

/**
* 
*/
class Tool2 extends Command
{
	protected function configure()
    {
        $this->setName('tool2')->setDescription('测试2');
    }
    /**
    	 * 批量推送 先找status=0的notice 再找status=0的notice_user
    	 */	
    protected function execute(Input $Input,Output $output)
    {
        // 所有的推送
        $noticeArr = [];
    	$notices = Db::table("cx_notice")->select();
        if($notices) {
            foreach ($notices as $key => $value) {
                $noticeArr[$value['id']] = $value;
            }
        }
        $page = 1;
        begin:
        // $time = time();
        $users = Db::table("cx_notice_user")->where("status=0")->page("$page,200")->select();
        // var_dump($users);exit;
        if($users) {
            foreach ($users as $key => $value) {
                if($value['form_id']) {
                    isset($noticeArr[$value['nid']]) && $this->send($value['openid'],$value['form_id'],$value['uid'],$noticeArr[$value['nid']],$value['id']);
                }
            }
            echo ($page*200+1)."=============";
            $page++;
            goto begin;
        } else{
            echo "finished";
        }
	    	
    }

    // $templateId='gjL_XoZBZgboU9gFdEOa-nRb9J2IuNc_-kJqi1C7l5E',
    public function send($openid='',$form_id='',$user_id='',$data=[],$nuid='')
    {
    	$token = $this->getAccessToken('wx6478de06dfe74f4e','3b036f1650a0b5f138f74feac1910b66');
        $types = [
	    1=>'杂志',
        2=>'小课',
        3=>'视频',
        4=>'活动'
	    ];
	    $objs = [
	    1=>'Magazine',
        2=>'Course',
        3=>'Course',
        4=>'Activity'
	    ];
	    $user_types = [
	    0=>'全部',
	    1=>'会员',
	    2=>'非会员'
	    ];
	    $paths = [
	    1=>'pages/magazine/maga_details',
	    2=>'pages/tutorial/tuto_details',
	    3=>'pages/tutorial/tuto_details',
        4=>'pages/activity/index'
	    ];
	    $Course= new \app\api\model\Course();
        $Magazine= new \app\api\model\Magazine();
        $TalkShow= new \app\api\model\TalkShow();
        $Activity= new \app\api\model\Activity();

        // $postUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=".$token;
        $postUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=".$token;
        // $thismodel = $objs[$type];
        // $data = $$thismodel->where(['id'=>$oid])->find();
        $info = [
            'touser' => $openid,
            'access_token'=>$token,
            'weapp_template_msg' => [
                // 'appid' => 'wxcec1c786e574362c',
                'template_id' => 'gjL_XoZBZgboU9gFdEOa-nRb9J2IuNc_-kJqi1C7l5E',
                'page'=>$paths[$data['type']]."?id=".$data['oid']."&id_send=1",
                'form_id'=>$form_id,
                'emphasis_keyword'=>"",
                'data' => [
                    'first'=>[
                        'color'=>'#173177',
                        'value'=>$data['head_txt'],
                    ],
                    'remark'=>[
                        'color'=>'#173177',
                        'value'=>$data['foot_txt'],
                    ],
                    'keyword1'=>[
                        'color'=>'#173177',
                        'value'=>$data['title'],
                    ],
                    'keyword2'=>[
                        'color'=>'#173177',
                        'value'=>$types[$data['type']],
                    ],
                    'keyword3'=>[
                        'color'=>'#173177',
                        'value'=>$data['foot_txt'],
                    ],
                ]
            ],
            // 'mp_template_msg'=>[
            //     'appid'=>$openid,
            //     'template_id'=>'jmChuaLHybl3RNO2nuYYK0fenYv6LyKE1cnQc3stKuA',
            //     'url'=>'',
            //     'miniprogram'=>[
            //         'appid'=>'wx6478de06dfe74f4e',
            //         'pagepath' => $paths[$data['type']]."?id=".$data['oid']
            //     ],
            //     'data' => [
            //         'first'=>[
            //             'color'=>'#173177',
            //             'value'=>$data['head_txt'],
            //         ],
            //         'remark'=>[
            //             'color'=>'#173177',
            //             'value'=>$data['foot_txt'],
            //         ],
            //         'keyword1'=>[
            //             'color'=>'#173177',
            //             'value'=>$data['title'],
            //         ],
            //         'keyword2'=>[
            //             'color'=>'#173177',
            //             'value'=>$types[$data['type']],
            //         ],
            //     ]
            // ]
        ];
		$postRes = $this->curl_post_https($postUrl, json_encode($info));
		$data = json_decode($postRes,true);
		if(!$data['errcode']) {
			Db::table("cx_notice_user")->where(['id'=>$nuid])->data(['status'=>1])->update();
            // 推送完成把这个formid删了
            // $user = Db('user')->where(['id'=>$user_id])->find();
            // if($user) {
            //     Db::table("cx_user")->where(['id'=>$user_id])->data(['form_id'=>$thisform_id])->update();
            // }
		}
        Log::write(json_encode($data));
    }

    public function checkCanSend($uid='')
    {
        $obj = $this->model->order("create_time desc")->find();
        if(!$obj) {
            json_success('没有设置推送');
        } else {
            $res = $this->NoticeUser->where(['uid'=>$uid,'oid'=>$obj['oid'],'type'=>$obj['type']])->find();
            if($res) {
                json_success('该用户已被推送过');
            } else {
                json_success(['status'=>1]);
            }
        }

    }

    public function curl_post_https($url,$data){ // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        // curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }

    public function getAccessToken($appid='',$apps='') {
        // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
        // $data = json_decode(file_get_contents("access_token.json"));
        $data = Cache::get('wechat_access_token') ? Cache::get('wechat_access_token') : (object)array('expire_time'=>0,'access_token'=>'');
        // var_dump($data);
        $access_token = '';
        if ($data->expire_time < time()) {
            // 如果是企业号用以下URL获取access_token
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$apps";
            $res = json_decode($this->httpGet($url));
            // var_dump($res);
            if (isset($res->access_token)) {
                $data->expire_time = time() + 7000;
                $access_token = $data->access_token = $res->access_token;
                Cache::set('wechat_access_token',$data, 7000);
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }

    public function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }
}